﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2017/2/4
 * 时间: 21:21
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Net;
using System.Text;
using System.IO;

namespace MiniHttpServer
{
	/// <summary>
	/// Description of HttpDealer.
	/// </summary>
	public class HttpDealer
	{
		Server server;
		HttpListenerRequest request;
		HttpListenerResponse response;

		public HttpListenerRequest Request {
			get {
				return request;
			}
			set {
				request = value;
			}
		}

		public HttpListenerResponse Response {
			get {
				return response;
			}
			set {
				response = value;
			}
		}

		public HttpDealer()
		{
		}
		
		public HttpDealer(Server server, HttpListenerRequest request, HttpListenerResponse response)
		{
			this.server = server;
			this.request = request;
			this.response = response;
		}
		
		public bool Deal()
		{
			// RawUrl是HTTP协议里面原始的访问URL（也就是从后面的路径部分）
			// Url是自动补全后的完整的整个路径（包含前面的协议头、IP和端口）
			if (request.RawUrl.StartsWith("/test", StringComparison.Ordinal))
			{
				return ShowTestPage();
			}
			else if (request.RawUrl.StartsWith("/help", StringComparison.Ordinal))
			{
				string url = HttpFile.GetUrlFile(request.RawUrl);
				if (url == "/help" || url == "/help/")
					url = "/help/index.html";
				return ShowResourcePage(url);
			}
			else if (request.RawUrl.StartsWith("/stopServer", StringComparison.Ordinal))
			{
				server.NeedStop = true;
				return ShowResourcePage("/stopServer");
			}
			else
			{
				var filter = new HttpFilter(server, request, response);
				if (filter.Filter())
				{
					return SendResponse(filter.ResponseContent);
				}
				else if (request.RawUrl.StartsWith("/", StringComparison.Ordinal))
				{
					return ShowResourcePage("/welcome/index.html");
				}
				else
				{
					SendErrorResponse(404, "Page Not Found");
					return false;
				}
			}
		}
		
		bool SendResponse(string content)
		{
			return SendResponse(Encoding.Default.GetBytes(content));
		}
		
		bool SendResponse(byte[] content)
		{
			var bw = new BinaryWriter(response.OutputStream);
			bw.Write(content, 0, content.Length);
			bw.Close();
			return true;
		}
		
		void SendErrorResponse(int code, string description)
		{
			response.StatusCode = code;
			response.StatusDescription = description;
			
			SendResponse(Encoding.Default.GetBytes(description));	//TODO 调取资源中的404页面
		}
		
		bool ShowTestPage()
		{
			Logger.WriteDebug("{0} url: {1}", request.HttpMethod, request.RawUrl);
			foreach (string key in request.QueryString.Keys)
			{
				Logger.WriteDebug("Para[" + key + "] = " + request.QueryString[key]);
			}
			if (request.HasEntityBody)
			{
				var sr = new StreamReader(request.InputStream);
				string content = sr.ReadToEnd();
				sr.Close();
				Logger.WriteDebug("Post Content: {0}", content);
			}
			
			string responseString = @"<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Mini HTTP Server Work OK!</h1>
<h3>Paras</h3>";
			foreach (string key in request.QueryString.Keys)
			{
				responseString += "Para[" + key + "] = " + request.QueryString[key] + "<br/>";
			}
			responseString += @"
<span><a href=""/test"" target=""_self"">Show Test Page</a></span>&nbsp;&nbsp;
<span><a href=""/help"" target=""_self"">Show Help Page</a></span>
</body>
</html>";
			return ShowTextPage(responseString);
		}
		
		bool ShowResourcePage(string pageName)
		{
			//TODO 需要根据pageName从PagesResource资源中提取数据
			//TODO 读取资源中的帮助页面相关的内容
			string responseString = "There is no this resource page yet, please wait";
			return ShowTextPage(responseString);
		}
		
		bool ShowTextPage(string text)
		{
			response.ContentLength64 = Encoding.Default.GetByteCount(text);
			response.ContentType = "text/html; charset=" + Encoding.Default.EncodingName;
			
			return SendResponse(text);
		}
	}
}
